//
//  ViewController.m
//  DabaiInsurance
//
//  Created by menchao on 16/7/28.
//  Copyright © 2016年 menchao. All rights reserved.
//

#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKUI/ShareSDK+SSUI.h>
#import "MBProgressHUD.h"
#import "DSNetWorkShareView.h"
#import "PlatformMacro.h"
#import "ErrorTipView.h"
#import "PopupManager.h"
#import <WebKit/WebKit.h>
#import "WXApi.h"
#import "SDWebImageManager.h"

@interface ViewController ()<UIWebViewDelegate,WKScriptMessageHandler, WKNavigationDelegate, WKUIDelegate>

@property (nonatomic, strong) JSContext *jsContext;
@property (nonatomic, copy) NSString *shareTitle;
@property (nonatomic, copy) NSString *iconUrl;
@property (nonatomic, copy) NSString *shareContent;
@property (nonatomic, copy) NSString *shareUrlLink;
@property (nonatomic, strong) TYAlertController *alertController;
@property(nonatomic,strong) UIBarButtonItem *leftBarButtonItem;
@property(nonatomic,strong) UIBarButtonItem *rightBarButtonItem;
@property (nonatomic,strong) ErrorTipView *errorTipView;
@property(nonatomic,copy) NSString * currentPageUrl;
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) UIProgressView *progressView;
@end

#define  BackButtonFrame     CGRectMake(0, 0, 10, 19)
#define  ShareButtonFrame    CGRectMake(ScreenWidth - 10, 0, 19, 19)
//#define  ServerAdress        @"http://cf.dabai360.com/"

#define  ServerAdress        @"http://wbg.zhenghu.cn/"




static  NSInteger   kTimers = 0;

@implementation ViewController

#pragma  mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];

    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)
                                      configuration:[self webConfig]];
    
    [self.view addSubview:self.webView];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    
    // 添加KVO监听
    [self.webView addObserver:self
                   forKeyPath:@"loading"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:@"title"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    [self.webView addObserver:self
                   forKeyPath:@"estimatedProgress"
                      options:NSKeyValueObservingOptionNew
                      context:nil];
    
    // 添加进度条
    self.progressView = [[UIProgressView alloc] init];
    self.progressView.frame = CGRectMake(0, 64, self.view.frame.size.width, 5);
    [self.view addSubview:self.progressView];
   
   // self.progressView.trackTintColor = [UIColor colorWithRed:227/255.0 green:227/255.0 blue:227/255.0 alpha:0.5];
   // self.progressView.tintColor = [UIColor colorWithRed:0/255.0 green:179/255.0 blue:134/255.0 alpha:1.0];
    
    self.progressView.trackTintColor = [UIColor colorWithRed:227/255.0 green:227/255.0 blue:227/255.0 alpha:0.5];
    self.progressView.tintColor = [UIColor colorWithRed:52/255.0 green:106/255.0 blue:196/255.0 alpha:1.0];

   // #346ac4   52   106  196
    //请求
    NSURLRequest *requeset = [NSURLRequest requestWithURL:[NSURL URLWithString:ServerAdress] ];
    [self.webView loadRequest:requeset];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc{
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
}

- (WKWebViewConfiguration *)webConfig{
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    // 设置偏好设置
    config.preferences = [[WKPreferences alloc] init];
    // 默认为0
    config.preferences.minimumFontSize = 10;
    // 默认认为YES
    config.preferences.javaScriptEnabled = YES;
    // 在iOS上默认为NO，表示不能自动通过窗口打开
    config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    // web内容处理池
    config.processPool = [[WKProcessPool alloc] init];
    // 通过JS与webview内容交互
    config.userContentController = [[WKUserContentController alloc] init];
    //在WKScriptMessageHandler代理中接收到
    [config.userContentController addScriptMessageHandler:self name:@"wxshare"];
    return config;
}

#pragma mark - event

- (void)wechatShareType:(int )shareType
                  title:(NSString *)title
                  imageUrl:(NSString *)imageUrl
           shareContent:(NSString *)content
              shareLink:(NSString *)linkUrl{
#if 0
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    [shareParams SSDKSetupShareParamsByText:content
                                     images:imageUrl
                                        url:[NSURL URLWithString:[NSString stringWithFormat:@"%@",linkUrl]]
                                      title:title
                                       type:SSDKContentTypeWebPage];
    [ShareSDK share:shareType
         parameters:shareParams
     onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
         switch (state) {
             case SSDKResponseStateSuccess:
             {
                 [PopupManager showMessage:@"分享成功"];
                 break;

             }
             case SSDKResponseStateFail:
             {
                 [PopupManager showMessage:@"分享失败"];
                 break;
             }
             case SSDKResponseStateCancel:
             {
                 [PopupManager showMessage:@"分享取消"];
             }
             default:
                 break;
         }
     }];
#else
    WXWebpageObject * ext = [WXWebpageObject object];
    ext.webpageUrl = linkUrl;
    WXMediaMessage * message = [WXMediaMessage message];
    message.title = title;
    message.mediaObject = ext;
    message.description = content;
    SDWebImageManager * manager = [SDWebImageManager sharedManager];
    [manager downloadImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",imageUrl]] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
        [message setThumbImage:image];
        SendMessageToWXReq* req = [[SendMessageToWXReq alloc] init];
        req.bText = NO;
        req.message = message;
        req.scene = shareType;
        [WXApi sendReq:req];
    }];
#endif
    
}

- (void)backAction{
    if (_webView.canGoBack) {
        [_webView goBack];
    }
}

- (void)shareAction{
    DSNetWorkShareView *netWorkShareVc = [[DSNetWorkShareView alloc] init];
    netWorkShareVc.leftBtnBlock = ^(){
        //0 好友  1 朋友圈
        [self wechatShareType:WXSceneSession
                        title:self.shareTitle
                     imageUrl:self.iconUrl
                 shareContent:self.shareContent
                    shareLink:self.shareUrlLink];
        [self.alertController dismissViewControllerAnimated:YES];
    };
    netWorkShareVc.rightBtnBlock = ^(){
        [self wechatShareType:WXSceneTimeline
                        title:self.shareTitle
                     imageUrl:self.iconUrl
                 shareContent:self.shareContent
                    shareLink:self.shareUrlLink];
        [self.alertController dismissViewControllerAnimated:YES];
    };
    
    self.alertController = [TYAlertController alertControllerWithAlertView:netWorkShareVc preferredStyle:TYAlertControllerStyleActionSheet transitionAnimation:TYAlertTransitionAnimationFade];
    self.alertController.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    self.alertController.backgoundTapDismissEnable = YES;
    [self.navigationController presentViewController:self.alertController animated:YES completion:nil];
}

#pragma mark - UI


- (UIBarButtonItem *)barButtonItemWithImageName:(NSString *)imageName
                                          frame:(CGRect)frame
                                         target:(id)target
                                         action:(SEL)action{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
    button.frame = frame;
    [button setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
    [button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *buttonItem = [[UIBarButtonItem alloc]initWithCustomView:button];
    return buttonItem;
}

- (void)showBackButton:(BOOL)isShow{
    if (isShow) {
        self.navigationItem.leftBarButtonItem =  self.leftBarButtonItem;
    }else{
        self.navigationItem.leftBarButtonItem = nil;
    }
}


- (void)showShareButton:(BOOL)isShow{
    if (isShow) {
        self.navigationItem.rightBarButtonItem = self.rightBarButtonItem;
    }else{
        self.navigationItem.rightBarButtonItem = nil;
    }
}

- (UIBarButtonItem *)leftBarButtonItem{
    if (!_leftBarButtonItem) {
        _leftBarButtonItem = [self barButtonItemWithImageName:@"btn_fh" frame:BackButtonFrame target:self action:@selector(backAction)];
    }
    return _leftBarButtonItem;
}

- (UIBarButtonItem *)rightBarButtonItem{
    if (!_rightBarButtonItem) {
        _rightBarButtonItem = [self barButtonItemWithImageName:@"btn_fx" frame:ShareButtonFrame target:self action:@selector(shareAction)];
    }
    return _rightBarButtonItem;
}

- (ErrorTipView *)errorTipView{
    if (!_errorTipView) {
        _errorTipView = [[ErrorTipView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64)];
        [self.view addSubview:_errorTipView];
        [_errorTipView tapAction:^{
            
            
        }];
    }
    return _errorTipView;
}

- (NSString *)currentPageUrl{
    if (IsEmptyString(_currentPageUrl)) {
        return ServerAdress;
    }
    return _currentPageUrl;
}

- (void)showErrorView{
    [UIView animateWithDuration:0.3 animations:^{
        self.errorTipView.hidden = NO;
    } completion:^(BOOL finished) {
    }];
    
    [self.errorTipView tapAction:^{
        NSURLRequest *requeset = [NSURLRequest requestWithURL:[NSURL URLWithString:self.currentPageUrl] ];
        [_webView loadRequest:requeset];
    }];
}

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"wxshare"]) {
        // NSDictionary, and NSNull类型
        NSDictionary *dict = message.body;
        NSLog(@"wxshare %@", dict);
        if (dict) {
            __weak typeof(self) weakSelf = self;
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.shareTitle = dict[@"title"];
                weakSelf.iconUrl = dict[@"imageUrl"];;
                weakSelf.shareContent = dict[@"shareContent"];
                weakSelf.shareUrlLink = dict[@"shareUrlLink"];
                [weakSelf shareAction];
            });
        }
    }else if([message.name isEqualToString:@"showBack"]){
        NSNumber *number = message.body;
        if (number) {
             [self showBackButton:number.intValue>0?YES:NO];
        }
    }
}

#pragma mark - KVO

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary<NSString *,id> *)change
                       context:(void *)context {
    if ([keyPath isEqualToString:@"loading"]) {
        self.progressView.alpha = 1;
    } else if ([keyPath isEqualToString:@"title"]) {
        self.title = self.webView.title;
    } else if ([keyPath isEqualToString:@"estimatedProgress"]) {
        NSLog(@"progress: %f", self.webView.estimatedProgress);
        self.progressView.progress = self.webView.estimatedProgress;
    }
    // 加载完成
    if (!self.webView.loading) {
        [UIView animateWithDuration:0.5 animations:^{
            self.progressView.alpha = 0;
            self.progressView.progress = 0.0;
        }];
    }
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
     self.currentPageUrl = webView.URL.absoluteString;
    NSLog(@"currentPageUrl %@",self.currentPageUrl);
    if (kTimers == 0) {
        [PopupManager showMessageWithLoading:@"数据加载中"];
    }
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error{
    if (kTimers == 0) {
        kTimers = 1;
        [PopupManager hideHUD];
    }
    NSLog(@"进入失败方法");
    if (error) {
        NSLog(@"进入错误");
        [self showErrorView];
    }else{
        
    }
     
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
    NSLog(@"%s", __FUNCTION__);
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    if (!self.errorTipView.hidden) {
       self.errorTipView.hidden = YES;
    }
    [self showBackButton:webView.canGoBack?YES:NO];
    if (kTimers == 0) {
        kTimers = 1;
        [PopupManager hideHUD];
    }
}

//拦截JS
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    NSLog(@"runJavaScriptAlertPanelWithMessage %@", message);
    if (completionHandler) {
        completionHandler();
    }
}


/*
#pragma mark- webview delegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType{

    //NSLog(@"URL %@",request.URL);
    
   
    //self.urlStr = [NSString stringWithFormat:@"%@",request.URL];
    
    self.currentPageUrl = request.URL.absoluteString;
    
    //NSLog(@"webView.canGoBack %d",webView.canGoBack);

    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView{
    [[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    _jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//    __weak typeof(self) weakSelf = self;
//    _jsContext[@"wechatShare"] = ^(NSString *title,NSString *imageUrl,NSString *shareContent,NSString *shareUrlLink) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            weakSelf.shareTitle = title;
//            weakSelf.iconUrl = imageUrl;
//            weakSelf.shareContent = shareContent;
//            weakSelf.shareUrlLink = shareUrlLink;
//            NSLog(@"title %@ %@ %@ %@",title,imageUrl,shareContent,shareUrlLink);
//            
//            [weakSelf shareAction];
//        });
//    };

    
//    _jsContext[@"showShareIcon"] = ^(NSInteger isShow) {
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [weakSelf showShareButton:isShow];
//        });
//    };

    
    
        //[PopupManager showMessageWithLoading:@"数据加载中"];
 
    if (kTimers == 0) {
        [PopupManager showMessageWithLoading:@"数据加载中"];
    }
}


- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
    [self showBackButton:webView.canGoBack?YES:NO];
    
    
    __weak typeof(self) weakSelf = self;
    weakSelf.title= [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    self.errorTipView.hidden = YES;

    //
    _jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
      _jsContext[@"wechatShare"] = ^(NSString *title,NSString *imageUrl,NSString *shareContent,NSString *shareUrlLink) {
        dispatch_async(dispatch_get_main_queue(), ^{
            weakSelf.shareTitle = title;
            weakSelf.iconUrl = imageUrl;
            weakSelf.shareContent = shareContent;
            weakSelf.shareUrlLink = shareUrlLink;
            NSLog(@"title %@ %@ %@ %@",title,imageUrl,shareContent,shareUrlLink);
            
            [weakSelf shareAction];
        });
    };

    //[PopupManager hideHUD];

    if (kTimers == 0) {
        kTimers = 1;
        [PopupManager hideHUD];
    }

}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(nullable NSError *)error{
    NSLog(@"webView  error %@",error);
    if (kTimers == 0) {
        kTimers = 1;
        [PopupManager hideHUD];
    }
    [self showErrorView];
}

- (void)showErrorView{
    [UIView animateWithDuration:0.3 animations:^{
        self.errorTipView.hidden = NO;
    } completion:^(BOOL finished) {
    }];
    
    [self.errorTipView tapAction:^{
        NSURLRequest *requeset = [NSURLRequest requestWithURL:[NSURL URLWithString:self.currentPageUrl] ];
        [_webView loadRequest:requeset];
    }];
}

*/

@end
